<?php
namespace api\xcx\controller;
use think\Cache;
use think\Loader;
use think\Db;
use think\Request;
use think\Controller;
use think\config;
/**
 *  Xcx.php 有关小程序的操作 
 *
 * @copyright			(C) 2014-2018 ShengTeng
 * @lastmodify			2018-06-21
 */
class Xcx extends Base
{

    /**
     * @api {POST} Xcx/xcxlogin 登录
     * @apiVersion 1.0.0
     * @apiGroup xcx
     *
     * @apiParam {String} code 小程序的code
     * @apiParam {String} name 昵称
     * @apiParam {String} pic 头像
     * @apiParam {Int} sex 性别 1女2男
     *
     * @apiSuccess {Int} code 返回码
     * @apiSuccess {String} message  提示信息
     * @apiSuccess {Object} data  返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code":0,
     *          "message":"",
     *          "data":{
     *              token 请求数据使用,
     *              userName 用户昵称,
     *              userSex 用户性别 1，女，2，男,
     *              userPic 用户头像,
     *              status 用户状态 1：正常。2：禁用,
     *              userStatus 是否是vip 1：非VIP，2：vip,
     *              address 地址,
     *              userPhone 用户手机号,
     *              startTime vip开始时间,
     *              endTime vip结束时间,
     *              trueName 用户姓名,
     *              vipCard  vip卡号
     *          }
     *      }
     */     
    public function xcxlogin(Request $request){
        $params=$request->param();
        
        // 验证code
        $code = $this->checkParam($params['code'],'code',true);
        // 验证昵称
        $name =  $this->checkParam($params['name'],'name',false);
        // 验证头像
        $pic = $this->checkParam($params['pic'],'pic',false);
        // 验证性别
        $sex = $this->checkParam($params['sex'],'sex',false);
        // if($sex != 1 && $sex != 2 && $sex !=3){
        //     return json(returnAjax('','参数sex不是有效值',1));
        // }
        $xcxinfo = Config::get('xcxinfo');
        $appid=  $xcxinfo['appid'];
        $secret= $xcxinfo['secret'];
        $url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
        $data=doCurl($url);
        $openid = $data->openid;
        $unionid = $data->unionid;

        if(!$openid){
            return json(returnAjax('','系统错误',-1));
        }
        //根据openid和unionid查找用户
        $user = Model('User');
        $res = $user->login($openid,$unionid,$name,$sex,$pic);
        if($res || $res==[]){
            return json(returnAjax($res));
        }else{
            return json(returnAjax('','系统异常',-1));
        }
    }


    /**
     * @api {POST} Xcx/pay_order 支付
     * @apiVersion 1.0.0
     * @apiGroup xcx
     *
     * @apiParam {String} token 用户标识
     * @apiParam {String} crsNo 订单号
     * @apiParam {int} type 支付类型1开通vip,3预约
     *
     * @apiSuccess {Int} code 返回码
     * @apiSuccess {String} message  提示信息
     * @apiSuccess {Object} data  返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code":0,
     *          "message":"",
     *          "data":{
     *               "state": 1, 状态
     *               "timeStamp": "1556085653",时间戳
     *               "nonceStr": "4rbHyAmKfFIVytuTXJMP2gkZrYNw2gdr",
     *               "signType": "MD5",统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
     *               "package": "prepay_id=wx24140054414774c5e706f1773108021379",
     *               "paySign": "17C8F3527F71433920304CAA310C4EDF",//签名
     *               "out_trade_no": "15560856439"//订单号
     *          }
     *      }
     */
    public function pay_order(Request $request){

        $params=$request->param();
        // 验证token
        if(!isset($params['token'])){
            return json(returnAjax('','缺少参数token','1'));
        }
        $token = $params['token'];
        // 验证订单号
        if(!isset($params['crsNo'])){
            return json(returnAjax('','缺少参数crsNo','1'));
        }
        $crsNo = $params['crsNo'];
        // 验证类型
        if(!isset($params['type'])){
            return json(returnAjax('','缺少参数type','1'));
        }
        $type = $params['type'];
        if($type != 1  && $type != 3 ){
            return json(returnAjax('','type无效','1'));
        }
        // 根据token查询用户id
        $user = Model('User');
        $userInfo = $user->getopenId($token);
        if(!$userInfo){
            return json(returnAjax('','未找到该用户','1'));
        }
        $data['openid'] = $userInfo['openId'];

        $pay = new Pay();
        $xcxinfo = Config::get('xcxinfo');
        if($type==1){//开通会员
            // 根据订单号获取订单信息
            $vipOrder = Model('Viporder');
            $viporderInfo = $vipOrder->vip_order_info($crsNo);
            if(!$viporderInfo){
                return json(returnAjax('','未找到该订单','1'));
            }

            if($viporderInfo['status'] == 2){
                return json(returnAjax('','订单已支付','1'));
            }


            $data['crsNo'] = $viporderInfo['orderNumber'];
            $data['data_total'] = $viporderInfo['amount'];
             /* 调用微信【统一下单】 */
            $pay->pay($data['data_total']*100,$data['openid'],$data['crsNo'],$xcxinfo['domurl'].'Xcx/vip_notify_url');
        }else if($type==2){
           
        }else if($type == 3){//预约
            // 根据订单号获取订单信息
            $appointment = Model('Appointment');
            $appointmentInfo = $appointment->order_info($crsNo);
            if(!$appointmentInfo){
                return json(returnAjax('','未找到该订单','1'));
            }

            if($appointmentInfo['payStatus'] == 2){
                return json(returnAjax('','订单已支付','1'));
            }

            $data['crsNo'] = $appointmentInfo['orderNumber'];
            $data['data_total'] = $appointmentInfo['money'];
            /* 调用微信【统一下单】 */
            $pay->pay($data['data_total']*100,$data['openid'],$data['crsNo'],$xcxinfo['domurl'].'Xcx/appointment_notify_url');
        }
    }




     /**
     * @api {POST} Xcx/pay_order_server 服务单支付
     * @apiVersion 1.0.0
     * @apiGroup xcx
     *
     * @apiParam {String} token 用户标识
     * @apiParam {String} crsNo 订单号
     * @apiParam {double} reward 打赏金额(非必传)
     *
     * @apiSuccess {Int} code 返回码
     * @apiSuccess {String} message  提示信息
     * @apiSuccess {Object} data  返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code":0,
     *          "message":"",
     *          "data":{
     *               "state": 1, 状态
     *               "timeStamp": "1556085653",时间戳
     *               "nonceStr": "4rbHyAmKfFIVytuTXJMP2gkZrYNw2gdr",
     *               "signType": "MD5",统一下单接口返回的 prepay_id 参数值，提交格式如：prepay_id=*
     *               "package": "prepay_id=wx24140054414774c5e706f1773108021379",
     *               "paySign": "17C8F3527F71433920304CAA310C4EDF",//签名
     *               "out_trade_no": "15560856439"//订单号
     *          }
     *      }
     */
        public function pay_order_server(Request $request){
            $params=$request->param();
            // 验证token
            if(!isset($params['token'])){
                return json(returnAjax('','缺少参数token','1'));
            }
            $token = $params['token'];
            // 验证订单号
            if(!isset($params['crsNo'])){
                return json(returnAjax('','缺少参数crsNo','1'));
            }
            $reward = 0;
            $reward = $params['reward'];
            $crsNo = $params['crsNo'];
            // 用户信息
            $user = Model('user');
            $userInfo = $user->getAllInfo($token);
            if(!$userInfo){
                return json(returnAjax('','用户不存在','10'));
            }
            $order = Model('Order');//订单信息
            $xcxinfo = Config::get('xcxinfo');
            $orderInfo = $order->order_info($crsNo);


            if($orderInfo['payStatus']==2){
                return json(returnAjax('','订单已支付','1'));
            }

            $payMoney = 0;
            if(!$orderInfo['userId']){
                if($userInfo['userStatus'] ==2){
                    $payMoney = $orderInfo['vipAmount'];
                }else{
                    $payMoney = $orderInfo['amount'];
                }
                $orderData['userId'] = $userInfo['userId'];
            }else{
                $payMoney = $orderInfo['vipAmount'];
            }
            if(!$orderInfo){
                return json(returnAjax('','未找到该订单','1'));
            }
            $data['crsNo'] = $orderInfo['orderNumber'];
            $data['data_total'] = $payMoney+$reward;
            $orderData['reward'] = $reward;
            $orderData['userStatus'] = $userInfo['userStatus'];
            $payOrder =  time().'2'.$userInfo['userId'].random(2,1);
            $orderData['orderNumberPay'] = $payOrder;


            $goodsPrice = $orderInfo['commodityPrice'];
            $orderData['acommondityIncome'] = $goodsPrice;
            if($userInfo['userStatus']==2){
                // 获取项目折扣信息
                $goods_id = $orderInfo['acommondityId'];
                $goods_discount = $orderInfo['commondityDiscount'];
                $discount = explode(',',$goods_discount);
                $goodsId = explode(',',$goods_id);
                $goodsPrices = explode(',',$goodsPrice);
                $goodsIncome = array();
                $shopConfig = Model('ShopConfig');
                $shopId = $orderInfo['shopId'];
                for($i=0;$i<count($goodsId);$i++){
                    // // 获取每个项目的信息
                    // if($goodsId[$i] == 1){
                    //      array_push($goodsIncome,0);
                    // }else if($goodsId[$i] == 2){
                    //      // 获取纯色价格
                    //      $pure = $shopConfig->getPureInfo($shopId);
                    //      $purePrice = $pure['shopMoney'];
                         
                    //      array_push($goodsIncome,($goodsPrices[$i]-$purePrice)*$discount[$i]);
                    // }else{
                    //      array_push($goodsIncome,$goodsPrices[$i]*$discount[$i]);
                    // }
                    array_push($goodsIncome,$goodsPrices[$i]*$discount[$i]);
               }
                $orderData['acommondityIncome'] = implode(',',$goodsIncome);
            }
            // 修改订单信息
            $upd = $order->orderUpd($crsNo,$orderData);
            if($upd){
                $pay = new Pay();
                /* 调用微信【统一下单】*/
                $pay->pay($data['data_total']*100,$userInfo['openId'],$payOrder,$xcxinfo['domurl'].'Xcx/order_notify_url');
            }else{
                return json(returnAjax('','系统错误','-1'));
            }
        }


    /**
     * 开通会员回调
     */
    public function vip_notify_url(){
            $pay = new Pay();
            
            //获取返回的xml
            $post = file_get_contents("php://input");
        
            setLog($post,'orderPay');


            // $post = "<xml><appid><![CDATA[wx853c31cec9f94388]]></appid>
            // <bank_type><![CDATA[CFT]]></bank_type>
            // <cash_fee><![CDATA[1]]></cash_fee>
            // <fee_type><![CDATA[CNY]]></fee_type>
            // <is_subscribe><![CDATA[N]]></is_subscribe>
            // <mch_id><![CDATA[1488509242]]></mch_id>
            // <nonce_str><![CDATA[sBpRxaUp0ncQQV1eQxY3FPZ03PpywSnc]]></nonce_str>
            // <openid><![CDATA[oMTAQ0dFkT7XGL2MD__USTfRESVY]]></openid>
            // <out_trade_no><![CDATA[155636738214]]></out_trade_no>
            // <result_code><![CDATA[SUCCESS]]></result_code>
            // <return_code><![CDATA[SUCCESS]]></return_code>
            // <sign><![CDATA[A298D5FB421DFFDF6F13926B93AA2EBE]]></sign>
            // <time_end><![CDATA[20190427201720]]></time_end>
            // <total_fee>1</total_fee>
            // <trade_type><![CDATA[JSAPI]]></trade_type>
            // <transaction_id><![CDATA[4200000321201904275708682978]]></transaction_id>
            // </xml>";
            $post_data = $pay->xml_to_array($post);   //微信支付成功，返回回调地址url的数据：XML转数组Array
            $postSign = $post_data['sign'];
            unset($post_data['sign']);

            /* 微信官方提醒：
             *  商户系统对于支付结果通知的内容一定要做【签名验证】,
             *  并校验返回的【订单金额是否与商户侧的订单金额】一致，
             *  防止数据泄漏导致出现“假通知”，造成资金损失。
             */
            ksort($post_data);// 对数据进行排序
            $str = $pay->ToUrlParams($post_data);//对数组数据拼接成key=value字符串
            $user_sign = strtoupper(md5($str));   //再次生成签名，与$postSign比较
            
            setLog($post_data,'orderPay');

            $out_trade_no = $post_data['out_trade_no'];
            $wxorder = $post_data['transaction_id'];

            if($post_data['return_code']=='SUCCESS' && $postSign){
                
                $vip_order = Model('Viporder');
                $vipInfo = $vip_order->vip_order_info($out_trade_no);
                // 修改订单号
                /*
                * 首先判断，订单是否已经更新为ok，因为微信会总共发送8次回调确认
                * 其次，订单已经为ok的，直接返回SUCCESS
                * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
                */
                if($vipInfo['status']=='2'){
                    $pay->return_success();
                }else{
                    $regionId = $vipInfo['regionId'];//区域id
                    $regionjc = 'qj';
                    if($regionId){
                        $region = Model('region');
                        $regionInfo = $region->regionInfoById($regionId);
                        if($regionInfo){
                            $regionjc = $regionInfo['regionLogogram'];
                        }
                    }else{
                        setLog('获取区域id失败','orderPay');
                    }
                        $userId = $vipInfo['userId'];//用户id
                        $user_data['userId'] = $userId;
                        $day = $vipInfo['duration'];//vip月数
                        $num = $vipInfo['vipNum'];//vip优惠次数
                        $nowDate = getNowDate();
                        $over_time = future_time($nowDate,$day);
                        $user_data['startTime'] = $nowDate;
                        $user_data['endTime'] = $over_time;
                        $user_data['userStatus'] = 2;
                        $user_data['vipNum'] = $num;
                        $user = Model('User');
                        // 获取用户信息
                        $userInfo = $user->getInfoById($userId);
                        if($userInfo){
                             // 更新订单状态
                            $vip_order_update = $vip_order->vip_order_update($out_trade_no,2,$wxorder,$user_data,$regionjc);
                            if($vip_order_update){
                                $pay->return_success();
                            }else{
                                setLog('无法修改订单信息-pay','orderPay');
                            }
                        }else{
                            setLog('获取用户信息失败','orderPay');
                            return;
                        }
                       
                }
            }else{
                echo '微信支付失败';
            }
    }


    /**
     * 服务回调
     */
    public function order_notify_url(){
            $pay = new Pay();
            
            //获取返回的xml
            $post = file_get_contents("php://input");
        
            setLog($post,'orderPayorder');
            // $post = "<xml><appid><![CDATA[wx853c31cec9f94388]]></appid>
            // <bank_type><![CDATA[CFT]]></bank_type>
            // <cash_fee><![CDATA[2]]></cash_fee>
            // <fee_type><![CDATA[CNY]]></fee_type>
            // <is_subscribe><![CDATA[N]]></is_subscribe>
            // <mch_id><![CDATA[1488509242]]></mch_id>
            // <nonce_str><![CDATA[BJPN3BxvbprVeZk7ivCGswacBsRTNCUX]]></nonce_str>
            // <openid><![CDATA[oMTAQ0dFkT7XGL2MD__USTfRESVY]]></openid>
            // <out_trade_no><![CDATA[1556126489214]]></out_trade_no>
            // <result_code><![CDATA[SUCCESS]]></result_code>
            // <return_code><![CDATA[SUCCESS]]></return_code>
            // <sign><![CDATA[D3EF02D84F17094A8BB129C250E95894]]></sign>
            // <time_end><![CDATA[20190425012210]]></time_end>
            // <total_fee>2</total_fee>
            // <trade_type><![CDATA[JSAPI]]></trade_type>
            // <transaction_id><![CDATA[4200000338201904255483622317]]></transaction_id>
            // </xml";
            $post_data = $pay->xml_to_array($post);   //微信支付成功，返回回调地址url的数据：XML转数组Array
            $postSign = $post_data['sign'];
            unset($post_data['sign']);

            /* 微信官方提醒：
             *  商户系统对于支付结果通知的内容一定要做【签名验证】,
             *  并校验返回的【订单金额是否与商户侧的订单金额】一致，
             *  防止数据泄漏导致出现“假通知”，造成资金损失。
             */
            ksort($post_data);// 对数据进行排序
            $str = $pay->ToUrlParams($post_data);//对数组数据拼接成key=value字符串
            $user_sign = strtoupper(md5($str));   //再次生成签名，与$postSign比较
            
            setLog($post_data,'orderPayorder');

            $out_trade_no = $post_data['out_trade_no'];
            $wxorder = $post_data['transaction_id'];
            $payTime = payTimeTo($post_data['time_end']);
            $payPrice = $post_data['total_fee']/100;

            if($post_data['return_code']=='SUCCESS' && $postSign){
               
                $order = Model('Order');
                $orderInfo = $order->order_info_server($out_trade_no);

                $xcxinfo = Config::get('xcxinfo');
                
                if($orderInfo['payStatus'] == 2){
                    $pay->return_success();
                }else{
                    switch ($orderInfo['type']) {
                        case '1'://上门订单
                                //根据用户信息判断用户的状态,如果是vip,查看补贴次数,如果,则添加补贴
                                $subsidy = 0;
                                $has_subsidy = false;
                                if($orderInfo['userStatus'] == 2 && $orderInfo['reward']>0){
                                    $user = Model('User');
                                    $userInfo = $user->getInfoById($orderInfo['userId']);
                                    if($userInfo['vipNum']>0){
                                       $subsidy =  $xcxinfo['subsidy'];
                                       $has_subsidy = true;
                                    }
                                }
                                $date = getNowDate();
                                $data['subsidy'] =  $subsidy;
                                $data['discountMoney'] = $payPrice;
                                $data['shopIncome'] = ($payPrice+$subsidy)/100*80;
                                $data['systemIncome'] = ($payPrice+$subsidy)/100*20;
                                $data['updtime'] = $date;
                                $data['payStatus'] = 2;
                                $data['status'] = 3;
                                $data['paytime'] = $payTime;
                                $data['wxOrder'] = $wxorder;
                                $data['paymentWay'] = 1;
                                $updOrder = $order->upd_door_pay($data,$out_trade_no,$has_subsidy,$orderInfo['userId']);
                                if($updOrder ){
                                        $pay->return_success();
                                }else{
                                    setLog('无法修改上门订单信息','orderPayorder');
                                }
                            break;
                        case '2'://到店订单
                                $subsidy = 0;
                                $has_subsidy = false;
                                if($orderInfo['userStatus'] == 2 && $orderInfo['reward']>0){
                                    $user = Model('User');
                                    $userInfo = $user->getInfoById($orderInfo['userId']);
                                    if($userInfo['vipNum']>0){
                                        $subsidy =  $xcxinfo['subsidy'];
                                        $has_subsidy = true;
                                    }
                                }
                                $date = getNowDate();
                                $data['subsidy'] =  $subsidy;
                                $data['discountMoney'] = $payPrice;
                                $data['shopIncome'] = ($payPrice+$subsidy)/100*80;
                                $data['systemIncome'] = ($payPrice+$subsidy)/100*20;
                                $data['updtime'] = $date;
                                $data['updtime'] = $date;
                                $data['payStatus'] = 2;
                                $data['paymentWay'] = 1;
                                $data['status'] = 3;
                                $data['wxOrder'] = $wxorder;
                                $data['paytime'] = $payTime;
                                $updOrder = $order->upd_shop_pay($data,$out_trade_no,$orderInfo['shopId'],$has_subsidy,$orderInfo['userId']);
                                if($updOrder ){
                                        $pay->return_success();
                                }else{
                                    setLog('无法修改到店订单信息','orderPayorder');
                                }
                            break;
                        case '3'://陌客订单
                                $subsidy = 0;
                                $has_subsidy = false;
                                if($orderInfo['userStatus'] == 2 && $orderInfo['reward']>0){
                                    $user = Model('User');
                                    $userInfo = $user->getInfoById($orderInfo['userId']);
                                    if($userInfo['vipNum']>0){
                                        $subsidy =  $xcxinfo['subsidy'];
                                        $has_subsidy = true;
                                    }
                                }
                                $date = getNowDate();
                                $data['subsidy'] =  $subsidy;
                                $data['discountMoney'] = $payPrice;
                                $data['shopIncome'] = ($payPrice+$subsidy)/100*80;
                                $data['systemIncome'] = ($payPrice+$subsidy)/100*20;
                                $data['updtime'] = $date;
                                $data['payStatus'] = 2;
                                $data['status'] = 3;
                                $data['wxOrder'] = $wxorder;
                                $data['paytime'] = $payTime;
                                $data['paymentWay'] = 1;
                                $updOrder = $order->upd_door_pay($data,$out_trade_no,$has_subsidy,$orderInfo['userId']);
                                if($updOrder){
                                        $pay->return_success();
                                }else{
                                    setLog('无法陌客订单信息','orderPayorder');
                                }
                            break;
                    }
                }
            }else{
                echo '微信支付失败';
            }
    }


    /**
     * 预约回调
     */
    public function appointment_notify_url(){
        $pay = new Pay();
            
            //获取返回的xml
            $post = file_get_contents("php://input");
        
            setLog($post,'appointOrder');
            // $post = "<xml><appid><![CDATA[wx853c31cec9f94388]]></appid>
            // <bank_type><![CDATA[CFT]]></bank_type>
            // <cash_fee><![CDATA[2]]></cash_fee>
            // <fee_type><![CDATA[CNY]]></fee_type>
            // <is_subscribe><![CDATA[N]]></is_subscribe>
            // <mch_id><![CDATA[1488509242]]></mch_id>
            // <nonce_str><![CDATA[BJPN3BxvbprVeZk7ivCGswacBsRTNCUX]]></nonce_str>
            // <openid><![CDATA[oMTAQ0dFkT7XGL2MD__USTfRESVY]]></openid>
            // <out_trade_no><![CDATA[1556126489214]]></out_trade_no>
            // <result_code><![CDATA[SUCCESS]]></result_code>
            // <return_code><![CDATA[SUCCESS]]></return_code>
            // <sign><![CDATA[D3EF02D84F17094A8BB129C250E95894]]></sign>
            // <time_end><![CDATA[20190425012210]]></time_end>
            // <total_fee>2</total_fee>
            // <trade_type><![CDATA[JSAPI]]></trade_type>
            // <transaction_id><![CDATA[4200000338201904255483622317]]></transaction_id>
            // </xml";
            $post_data = $pay->xml_to_array($post);   //微信支付成功，返回回调地址url的数据：XML转数组Array
            $postSign = $post_data['sign'];
            unset($post_data['sign']);

            /* 微信官方提醒：
             *  商户系统对于支付结果通知的内容一定要做【签名验证】,
             *  并校验返回的【订单金额是否与商户侧的订单金额】一致，
             *  防止数据泄漏导致出现“假通知”，造成资金损失。
             */
            ksort($post_data);// 对数据进行排序
            $str = $pay->ToUrlParams($post_data);//对数组数据拼接成key=value字符串
            $user_sign = strtoupper(md5($str));   //再次生成签名，与$postSign比较
            
            setLog($post_data,'appointOrder');

            $out_trade_no = $post_data['out_trade_no'];
            $wxorder = $post_data['transaction_id'];
            $payTime = payTimeTo($post_data['time_end']);

            if($post_data['return_code']=='SUCCESS' && $postSign){
               
                $appointment = Model('Appointment');
                $appointmentInfo = $appointment->order_info($out_trade_no);
                // 修改订单号
                /*
                * 首先判断，订单是否已经更新为ok，因为微信会总共发送8次回调确认
                * 其次，订单已经为ok的，直接返回SUCCESS
                * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
                */
                if($appointmentInfo['payStatus']=='2'){
                    $pay->return_success();
                }else{
                     // 更新订单状态
                    $order_update = $appointment->updPayStatus($out_trade_no,2,$wxorder,$payTime);
                    if($vip_order_update == true){
                            $pay->return_success();
                    }else{
                        setLog($order_update,'appointOrder');
                    }
                }
            }else{
                setLog('微信支付失败','appointOrder');
            }
    }









    /**
     * 接口调用凭证
     */
    public function access_token(){


        // 先获取数据库中的access_token
        $config = Model('Config');
        //查询access_token
        $info = $config->selByField('accessToken');
        if($info['value'] !=""){
            return $info['value'];
        }else{
            $xcxinfo = Config::get('xcxinfo');
            $appid =  $xcxinfo['appid'];
            $secret= $xcxinfo['secret'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            $res=doCurl($url);
            $data['value'] = $res->access_token;
            $data['updTime'] = getNowDate();
            $data['overTime'] =  date('Y-m-d H:i:s',strtotime("+1 hours"));
            $upd = $config->updByField('accessToken',$data);
            if($upd){
                $sel = $config->selByField('accessToken');
                if($sel['value'] !=""){
                    return $sel['value'];
                }else{
                    exit(json_encode(returnAjax('','获取凭证失败','-1')));
                }
            }else{
                exit(json_encode(returnAjax('','修改凭证失败'.$res->errcode,'-1')));
            }
        }
       
    }
/**
     * @api {POST} Xcx/getWxcode  生成二维码
     * @apiVersion 1.0.0
     * @apiGroup 微信
     *
     * @apiParam {String} path 页面地址
     * @apiParam {String} scene 参数
     * @apiParam {String} type 1邀请会员,2支付
     *
     * @apiSuccess {Int} code 返回码
     * @apiSuccess {String} message  提示信息
     * @apiSuccess {Object} data  返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *     {
     *          "code":0,
     *          "message":"",
     *          "data":{
     *              
     *             }
     *      }
     */

    public function getWxcode(Request $request)
{
        $params=$request->param();
        $path = $this->checkParam($params['path'],'path',true);
        $scene = $this->checkParam($params['scene'],'scene');
        $type = $this->checkParam($params['type'],'type');
        $access_token=$this->access_token();
        //生成二维码
        $width=300;
        $data = [
            'page'=>$path,
            "width"=>$width,
            'auto_color'=>false,
            'scene'=>$scene
            //'line_color'=>$line_color,
        ];
        $post_data= json_encode($data,true);
        $url="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
        $result=$this->api_notice_increment($url,$post_data);
        $img = $type.time().random(3)."code.png";
        $urls;
        $reurl;
        if($type==1){
            $urls = '../../public/code/vip/'.$img;
            $reurl = 'code/vip/'.$img;
        }else{
            $urls = '../../public/code/pay/'.$img;
            $reurl = 'code/pay/'.$img;
        }
        
        if(file_put_contents($urls, $result)){
            return json(returnAjax($reurl));
        }else{
            return json(returnAjax('','获取二维码失败','-1'));
        }
}

    public function send_post($url, $post_data,$method='POST') {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => $method, //or GET
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

    public function api_notice_increment($url,$data)
{
    $curl = curl_init();
    $a = strlen($data);
    $header = array("Content-Type: application/json; charset=utf-8","Content-Length: $a");
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl,CURLOPT_POST,1);
    curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;

}
}
